import { commands, window, languages, Uri, ViewColumn } from 'vscode'
import { CREATE_WEBVIEW, ADD_SINGLE_LANGUAGE_TEXT_DOC, SUBMIT_SINGLE_LANGUAGE_CODING } from '../contstants/Commands';
import { programMenusProvider } from '../ProgramMenusProvider';
import { twsManager } from '../TwsManager';
import { startAssignment, getAssignment, submitSingleOnlineCoding, getSingleOnlineCodingRunningLogs } from '../contstants/vscode-request';
import { selectWorkspaceFolder } from '../utils/WorkspaceUtil';
import * as fse from "fs-extra"
import { singleLanguageCodeingLensProvider } from '../SingleLanguageCodeingLensProvider';

export const toProgramDetail = (panel: any, params: any) => {
    postMessageToWebview(panel, { params, type: 'PROGRAM_DETAIL' })
}

export const toTaskDetail = (panel: any, item: any) => {
    postMessageToWebview(panel, {
        params: { taskId: item.id },
        type: 'TASK_DETAIL'
    })
    programMenusProvider.refreshAssignmentsMenus(item)
}
export const toAssignmentDetail = async (panel: any, item: any) => {
    if (!item.isStart) {
        const { userId, jwt, sessionId } = twsManager.getUser()
        startAssignment(item.taskId, item.id, userId, jwt, sessionId)
    }
    if (item.type === 'ONLINE_LANGUAGE_QUIZ') {
        const { jwt = '', sessionId = '' } = twsManager.getUser()
        const assignment = await getAssignment(item.id, jwt, sessionId)
        commands.executeCommand(ADD_SINGLE_LANGUAGE_TEXT_DOC, { ...assignment, taskId: item.id })
    }
    postMessageToWebview(panel, {
        type: 'ASSIGNMENT_DETAIL',
        params: { ...item }
    })
}

export const submitSingleLanguageCodingQuiz = (userSubmission: any) => {
    const channel = window.createOutputChannel('在线编程题')
    submitSingleOnlineCoding(userSubmission, (submissionId: number) => {
        window.showInformationMessage('提交成功，判题中...')
        channel.show()
        channel.appendLine(userSubmission.filePath)
        channel.appendLine(`判题中，请等待⌛️...`)
        getLog(userSubmission, submissionId, channel)
    })
}

const getLog = (userSubmission: any, submissionId: number, channel: any, preLog?: string) => {
    const { taskId, assignmentId, id } = userSubmission
    getSingleOnlineCodingRunningLogs(taskId, assignmentId, id, submissionId, (log: any) => {
        const { result, status } = log
        const isFinish = status === 0 || status === 2
        printLog(channel, preLog, result)
        if (isFinish) {
            const message = `编译${status === 0 ? '失败' : '成功'}`
            window.showInformationMessage(message)
            channel.appendLine(message)
            return
        }
        setTimeout(() => getLog(userSubmission, submissionId, channel, result), 1000)
    })
}
const printLog = (channel: any, preLog: any, result: string) => {
    if (preLog) {
        const remainLog = result.slice(preLog.length)
        channel.append(remainLog)
        return
    }
    channel.append(result)
}
export const addConsoleLog = async (assignment: any) => {
    const language = getFileType(assignment.language)

    const filePath = await selectWorkspaceFolder() + `/${assignment.assignmentTitle}.${language}`
    if (!await fse.pathExists(filePath)) {
        const code = assignment.userAnswer ? assignment.userAnswer : assignment.initCode
        await fse.writeFile(filePath, code);
    }
    await window.showTextDocument(Uri.file(filePath), {
        preview: false,
        viewColumn: ViewColumn.Two
    })
    if (singleLanguageCodeingLensProvider.needRefresh()) {
        languages.registerCodeLensProvider(
            {
                language: assignment.language,
                scheme: "file"
            },
            singleLanguageCodeingLensProvider.init(assignment)
        )
    }
    singleLanguageCodeingLensProvider.init(assignment)
}

export const submitSingleLanguageCodingWithTreeBtn = async (userSubmission: any) => {
    const { id, selectedQuizzes, title, taskId } = userSubmission
    const { jwt = '', sessionId = '', userId } = twsManager.getUser()
    const assignment = await getAssignment(id, jwt, sessionId)
    const { language } = assignment
    const filePath = await selectWorkspaceFolder() + `/${title + '.' + getFileType(language)}`
    commands.executeCommand(SUBMIT_SINGLE_LANGUAGE_CODING, {
        assignmentId: id,
        language: language,
        taskId,
        userId,
        id: selectedQuizzes[0].quizId,
        userAnswerCode: await getFileContent(filePath),
        filePath
    })
}

export const toIndexPage = (panel: any) => {
    postMessageToWebview(panel, { type: 'LOGOUT' })
}
const postMessageToWebview = (panel: any, message: any) => {
    if (!panel || panel._isDisposed) {
        commands.executeCommand(CREATE_WEBVIEW, message)
    } else {
        panel.webview.postMessage(message)
    }
}

const getFileContent = async (filePath: string) => {
    if (!await fse.pathExists(filePath)) {
        window.showErrorMessage(`${filePath} 文件不存在`)
        return ''
    }
    return fse.readFileSync(filePath, 'utf8')
}
const getFileType = (language: string) => {
    return language === 'javascript' ? 'js' : 'java'
}